package com.jeesite.modules.kj.api.controller;

import com.jeesite.common.config.Global;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.file.entity.FileEntity;
import com.jeesite.modules.file.entity.FileUpload;
import com.jeesite.modules.kj.api.controller.base.ApiBaseController;
import com.jeesite.modules.kj.api.enumCode.UnicomResponseEnums;
import com.jeesite.modules.kj.api.vo.responseVo.ResponseBean;
import com.jeesite.modules.kj.file.model.FileModel;
import com.jeesite.modules.kj.file.service.FileService;
import com.jeesite.modules.kj.file.service.KjFileUploadService;
import com.jeesite.modules.kj.file.utils.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 文件APIController
 * @author HZY
 * @version 2019-06-03
 */
@RestController
@RequestMapping(value = "api/file")
@Api(value="文件相关APIcontroller",tags={"文件相关API接口"})
public class FileApiController extends ApiBaseController {

    @Value("${file.baseDir}")
    private String baseDir;

    @Value("${file.url}")
    private String url;
    @Autowired
    FileService fileService;
    @Autowired
    KjFileUploadService kjFileUploadService;


//    @UserLoginToken
    @ApiOperation(value="上传文件",notes="上传文件")
    @PostMapping("/upload")
    @ResponseBody
    public ResponseBean<String> postUpload(MultipartFile file, String fileType) {
        // 获取文件的扩展名
        if(null !=file) {
            String md5 = null;

            String name = FilenameUtils.getName(file.getOriginalFilename());
            String ext = FilenameUtils.getExtension(file.getOriginalFilename());
            String path = DateUtils.getDate("yyyyMM") + "/";
            String contentType = file.getContentType();
            try {
                md5 = DigestUtils.md5Hex(file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(md5 != null) {

                FileEntity fileEntity = fileService.getDtoByMd5(md5);
                if(fileEntity == null){
                    fileEntity = new FileEntity();

                    fileEntity.setFileMd5(md5);
                    fileEntity.setFileExtension(ext);
                    fileEntity.setFilePath(path);
                    fileEntity.setFileContentType(contentType);
                    fileEntity.setFileSize(file.getSize());
                    if (contentType.equals("image/jpeg")) {
                        InputStream is = null;
                        try {
                            is = file.getInputStream();
                            BufferedImage buff = ImageIO.read(is);
                            int width = buff.getWidth();//得到图片的宽度
                            int height = buff.getHeight(); //得到图片的高度

                            is.close(); //关闭Stream
                            fileEntity.setFileMeta("{\"width\":" + width + ",\"height\":" + height + "}");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    fileService.insert(fileEntity);
                    try {
                        String s = FileUtils.uploadFile(file.getBytes(), baseDir, path, fileEntity.getId() + "." + ext);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                FileUpload fileUpload = new FileUpload();
                fileUpload.setFileEntity(fileEntity);
                fileUpload.setFileType(fileType);
                fileUpload.setFileName(name);
                fileUpload.setCreateBy("system");
                fileUpload.setCreateDate(new Date());
                fileUpload.setUpdateBy("system");
                fileUpload.setUpdateDate(new Date());
                kjFileUploadService.insert(fileUpload);
                return new ResponseBean(Global.TRUE, fileUpload.getId(), UnicomResponseEnums.SUCCESS_OPTION);
            }else{
                return new ResponseBean(Global.FALSE, "文件不存在", UnicomResponseEnums.FILE_NOTFOUND);
            }
        }
        else{
            return new ResponseBean(Global.FALSE, "文件不存在", UnicomResponseEnums.FILE_NOTFOUND);
        }
    }

    @ApiOperation(value="获取文件详情",notes="获取文件详情")
    @GetMapping("/{id}")
    public ResponseBean<FileModel> detail(@PathVariable("id") String id) {
        FileUpload fileUpload = kjFileUploadService.get(id);
        if(fileUpload != null)
        {
            FileModel fileModel = new FileModel(fileUpload, url);
            return new ResponseBean(fileModel);
        }else{
            return new ResponseBean(Global.FALSE, "文件不存在", UnicomResponseEnums.FILE_NOTFOUND);
        }
    }
    
    @ApiOperation(value="删除图片",notes="图片id")
    @DeleteMapping("/{id}")
    public ResponseBean<FileModel> delete(@PathVariable("id") String id) {
        FileUpload fileUpload = new FileUpload();
        fileUpload.setId(id);
        FileUpload fileUpload2 = kjFileUploadService.get(id);
        if(fileUpload2 != null){
        	 kjFileUploadService.delete(fileUpload);
        	 return new ResponseBean();
        }else{
        	return new ResponseBean(Global.FALSE, UnicomResponseEnums.FILE_NOTFOUND);
        }
    }

    @ApiOperation(value="获取文件列表",notes="获取文件列表")
    @GetMapping("/list")
    public ResponseBean<List<FileModel>> list(String bizKey, String bizType) {
        FileUpload fileUpload = new FileUpload();
        fileUpload.setBizKey(bizKey);
        fileUpload.setBizType(bizType);
        List<FileUpload> fileUploads = kjFileUploadService.findList(fileUpload);

        if(fileUploads != null)
        {
            List<FileModel> fileModels = new ArrayList<>();
            for (FileUpload fu: fileUploads
                    ) {
                fileModels.add(new FileModel(fu, url));
            }
            return new ResponseBean(fileModels);
        }else{
            return new ResponseBean(Global.FALSE, UnicomResponseEnums.FILE_NOTFOUND);
        }
    }


}
